package com.frogs.ucenter.util.record;

import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import com.frogs.system.web.api.entity.FeedsRecordActiveMqEntity;
/**
 * 发送用户动态记录
 * @author houlong
 *
 */
@Component("feedsRecordActiveMqSend")
public class FeedsRecordActiveMqSend {

	private static Logger logger = LoggerFactory.getLogger(FeedsRecordActiveMqSend.class);
	@Resource(name="feedsTemplate")
    private JmsTemplate jmsTemplate;
	
	/**
	 * 发送到队列
	 * @param feedsRecordActiveMqEntity
	 */
	public void sendToQueue(final FeedsRecordActiveMqEntity feedsRecordActiveMqEntity) {
		Session session = null;
		Connection connection = null;
		try {
			connection = jmsTemplate.getConnectionFactory().createConnection();//创建连接
			session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);//创建session
			String queueName = jmsTemplate.getDefaultDestinationName();//获取队列名
			Destination destination = session.createQueue(queueName);//创建队列
			Message message = session.createObjectMessage(feedsRecordActiveMqEntity);//创建发送内容
			session.createProducer(destination).send(message, DeliveryMode.PERSISTENT,5,5000000L);
		} catch (Exception e) {
			logger.error("func[send] smsMessageMqEntity[" + feedsRecordActiveMqEntity + "] e["+e.getMessage()+"] desc[fail]");
		} finally {  
            try {  
                if (null != connection)  
                    connection.close();  
                if (null != session)  
                	session.close();  
            } catch (Throwable ignore) { 
            	logger.error("func[send] ignore["+ignore.getMessage()+"] desc[fail]");
            }  
        }  
	}
	
	/**
	 * 发送消息
	 * @param actionRecord
	 * @param message
	 * @param familyId
	 * @param followedUserId
	 * @param followUserId
	 * @param type
	 */
	protected void send(String actionRecord, String message, int familyId , int followedUserId, int followUserId, int type) {
		logger.info("func[send] 推送消息,actionRecord[{}] message[{}] familyId[{}] followedUserId[{}] followUserId[{}] type[{}]", new Object[]{actionRecord, message, familyId, followedUserId,followUserId, type });
		FeedsRecordActiveMqEntity feedsRecordActiveMqEntity = new FeedsRecordActiveMqEntity();
		feedsRecordActiveMqEntity.setActionRecord(actionRecord);
		feedsRecordActiveMqEntity.setFamilyId(familyId);
		feedsRecordActiveMqEntity.setFollowedUserId(followedUserId);
		feedsRecordActiveMqEntity.setFollowUserId(followUserId);
		feedsRecordActiveMqEntity.setMessage(message);
		feedsRecordActiveMqEntity.setType(type);
		this.sendToQueue(feedsRecordActiveMqEntity);
    }
}
